﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;
using System.IO;

namespace RH
{
   public partial class wfProcPlaHoraMnt : EditPage
   {
      /// <summary>
      /// Guarda el estado de un DataTable, usado para llenar los dropdownlist del grdList.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public DataTable DataSourceDrop
      {
         get { return (DataTable)this.ViewState["_dsDrop"]; }
         set { this.ViewState["_dsDrop"] = value; }
      }

      /// <summary>
      /// Guarda el estado de un DataTable, usado para Guardar temporalmente data de un archivo Excel.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public DataTable DataSourceExcel
      {
         get { return (DataTable)this.ViewState["_dsXls"]; }
         set { this.ViewState["_dsXls"] = value; }
      }

      /// <summary>
      /// Guarda el estado de un DataTable, usado para Guardar Datos finales para ser guardados.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public DataTable DataSourceData
      {
         get { return (DataTable)this.ViewState["_dsData"]; }
         set { this.ViewState["_dsData"] = value; }
      }

      /// <summary>
      /// Guarda el estado de un string[], usado para guardar la Cadena de Conexion excel ah subir.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public string[] GetConnection
      {
         get { return (string[])this.ViewState["_dsFUpload"]; }
         set { this.ViewState["_dsFUpload"] = value; }
      }

      /// <summary>
      /// Guarda el estado de un string, usado para controlar el registro o modificacion de datos.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public string StDatosGenerados
      {
         get { return (string)this.ViewState["_dsDaGen"]; }
         set { this.ViewState["_dsDaGen"] = value; }
      }

      public const int _GRDLIST_IDHORA = 2;
      public const int _GRDLIST_STIDPERSONAL = 5;
      public const int _GRDLIST_STANULADO = 8;

      public const string _BUTTON_IMPORTFIELD = "_BTTIMPFIELD";
      public const string _BUTTON_IMPORTDATA = "_BTTIMPDATA";
      public const string _BUTTON_GENERATEDOC = "_BTTGENEDOC";

      protected void Page_Load(object sender, EventArgs e)
      {
         if (this.IsPostBack)
         {
            this.LoadInPostBack();
            return;
         }
         this.LoadData();
      }

      public override void LoadInPostBack()
      {
         foreach (GridViewRow gvr in this.grdListData.Rows)
         {
            if (gvr.RowType == DataControlRowType.DataRow)
            {

               int intIdx = 0;

               if (this.StDatosGenerados == ConstFlagEstado.ACTIVADO)
               {
                  foreach (DataRow dr in this.DataSource.Rows)
                  {
                     if ("" != dr["idHora"].ToString())
                     {
                        gvr.Cells[intIdx].Text = Request.Form[gvr.UniqueID + "$colum_" + gvr.RowIndex + "_" + intIdx.ToString()];
                     }
                     intIdx++;
                  }
               }
               else
               {
                  foreach (DataControlFieldCell dc in gvr.Cells)
                  {
                     if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "idPersonal" && ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "dsApeNombres")
                     {
                        dc.Text = Request.Form[gvr.UniqueID + "$colum_" + gvr.RowIndex + "_" + intIdx.ToString()];
                     }
                     intIdx++;
                  }

               }
            }
         }


         this.RegisterGeneralScripts();
      }

      public override void LoadInitialSettings()
      {
         this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
         this.SetInitialTitle("Horas Laboradas");
      
      }

      public override void LoadListControls()
      {
         EHora objE = new EHora();
         IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Hora));
         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         this.DataSourceDrop = objBO.GetList(objE);

      }

      public override void DataToControls()
      {
         EProcPlani objE = new EProcPlani();
         IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.ProcPlani));
         objE.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         objE.IdMes = Request.QueryString["IdMes"];
         objE.IdForPago = Request.QueryString["idForPago"];
         objE.IdPlanilla = Request.QueryString["IdPlanilla"];

         if (Request.QueryString["NuProcAnual"] != null)

            objE.NuProcAnual = Convert.ToInt16(Request.QueryString["NuProcAnual"]);

         this.txtNroProcAnual.Text = Request.QueryString["NuProcAnual"];
         objE = (EProcPlani)objBO.GetByKey(objE);


         if (objE != null)
         {
            WebHelper.EntityToControl(objE, "IdPlanilla", txtidPlanilla);

            EPlanilla objEPla = new EPlanilla();
            IBOQuery objBOPla = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Planilla));
            objEPla.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objEPla.IdPlanilla = Request.QueryString["IdPlanilla"];
            objEPla = (EPlanilla)objBOPla.GetByKey(objEPla);
            if (objEPla != null)
               WebHelper.EntityToControl(objEPla, "DsPlanilla", txtdsPlanilla);

         }

         MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));
         ETablaGenDet objEDet = new ETablaGenDet();
         objEDet.IdTabla = ConstMultitabla.FORMA_PAGO;
         objEDet.IdCodigo = Request.QueryString["idForPago"];
         objEDet = (ETablaGenDet)objBOI.GetDetailByKey(objEDet);

         if (objEDet != null)
            WebHelper.EntityToControl(objEDet, "DsDescrip", txtdsFormaPago);

         //EConfigHora objECH = new EConfigHora();
         //IBOQuery objBOCH = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(SYBOQry.ConfigHora));
         //objECH.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         //DataTable dt = objBOCH.GetList(objECH);
         //this.GridSetDataBinding(grdList, dt);

         EProcPlaHora objEPPH = new EProcPlaHora();
         IBOQuery objPPH = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.ProcPlaHora));
         objEPPH.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
         objEPPH.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         objEPPH.IdForPago = Request.QueryString["idForPago"];
         objEPPH.IdPlanilla = Request.QueryString["IdPlanilla"];

         if (Request.QueryString["NuProcAnual"] != null)
            objEPPH.NuProcAnual = Convert.ToInt16(Request.QueryString["NuProcAnual"]);

         this.DataSourceData = objPPH.GetList(objEPPH);

         if (this.DataSourceData.Rows.Count != 0)
         {
            this.grdListData.Columns.Clear();
            foreach (DataColumn drcol in this.DataSourceData.Columns)
            {
               BoundField bfield = new BoundField();
               bfield.DataField = drcol.Caption;

               switch (drcol.Caption)
               {
                  case "idPersonal":
                     bfield.HeaderText = "Codigo";
                     break;
                  case "dsApeNombres":
                     bfield.HeaderText = "Apellidos y Nombres";
                     break;
                  default:
                     DataRow[] dr = this.DataSourceDrop.Select("idHora = " + drcol.Caption);
                     if (dr.Length > 0)
                        bfield.HeaderText = dr[0]["dsHora"].ToString();

                     break;
               }

               this.grdListData.Columns.Add(bfield);
            }

            this.grdListData.DataSource = this.DataSourceData;
            this.grdListData.DataBind();
            this.tabMaster.ActiveTabIndex = 1;
            this.StDatosGenerados = ConstFlagEstado.DESACTIVADO;
         }
         else
         {
            this.tabMaster.ActiveTabIndex = 0;
            this.StDatosGenerados = ConstFlagEstado.DESACTIVADO;
         }

      }

      public override void RegisterGeneralScripts()
      {
         StringBuilder sb = new StringBuilder();

         sb.AppendLine("function validateEditForm(key){");

         sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
         sb.AppendLine("}");

         ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);
      }

      protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
      {
         if (e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_SAVE:
            case ConstMenuToolbarValue.BUTTON_SAVENEW:
               if (this.FormEditAction != FormEditAction.Delete)
                  this.SaveData(e.Item.Value);
               else
                  this.DeleteData();
               break;

            case ConstMenuToolbarValue.BUTTON_EXIT:
               this.Response.Redirect("wfProcPlaHoraBnd.aspx");
               break;
         }

      }

      public override void SaveData(String key)
      {
         if (this.ValidateData() == false)
            return;

         String[] strRet = null;

               IEntityBase objE = (IEntityBase)this.CreateEntitySet();
               IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.ProcPlaHora));
               strRet = objPro.UpdateData(objE);
           
         
         if (strRet == null)
            this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "Los Datos se guardaron correctamente", "wfImportDataBnd.aspx");
         else
            this.hdnMsgOPB.Value = this.CreatePostbackMessage(0, "- Los Codigos : \n" + strRet[0].ToString() + " No se encuentran registrados. \n", "wfImportDataBnd.aspx");

      }

      protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         if (e.Row.RowType == DataControlRowType.DataRow)
         {
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlidHora");
            WebHelper.LoadListControl(ddl, DataSourceDrop, "dsHora", "idHora", true, true);
            WebHelper.ListControlSetValue(ddl, e.Row.Cells[_GRDLIST_IDHORA].Text);
            RadioButton rdb = (RadioButton)e.Row.FindControl("rdbidPersonal");
            if (e.Row.Cells[_GRDLIST_STIDPERSONAL].Text == ConstFlagEstado.ACTIVADO)
               rdb.Checked = true;
         }
      }

      protected void grdListCampos_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         if (e.Row.RowType == DataControlRowType.Header)
         {
            CheckBox chkAllChecked = new CheckBox();
            chkAllChecked.ID = "chkAllCheck";
            chkAllChecked.Checked = false;
            chkAllChecked.Attributes.Add("onClick", "SelectedCheckBoxAll(this);");
            e.Row.Cells[0].Controls.Add(chkAllChecked);
         }
      }

      protected void grdListData_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         if (e.Row.RowType != DataControlRowType.DataRow)
            return;

         int intIdx = 0;

         if (this.StDatosGenerados == ConstFlagEstado.ACTIVADO)
         {
            foreach (DataRow dr in this.DataSource.Rows)
            {
               if ("" != dr["idHora"].ToString() && "dsObserva" != dr["idHora"].ToString() && "idConRemu" != dr["idHora"].ToString())
               {
                  esdNumericTextBox objNumText = new esdNumericTextBox();
                  objNumText.NumericType = NumericType.Decimal;
                  objNumText.Width = 30;
                  objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx.ToString();
                  objNumText.Text = e.Row.Cells[intIdx].Text;
                  e.Row.Cells[intIdx].Controls.Add(objNumText);
               }
               else
               {
                  if ("dsObserva" == dr["idHora"].ToString())
                  {
                     esdTextBox objNumText = new esdTextBox();
                     objNumText.Width = 150;
                     objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx.ToString();
                     objNumText.Text = e.Row.Cells[intIdx].Text;
                     e.Row.Cells[intIdx].Controls.Add(objNumText);
                  }
                  if ("idConRemu" == dr["idHora"].ToString())
                  {
                     esdTextBox objNumText = new esdTextBox();
                     objNumText.Width = 30;
                     objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx.ToString();
                     objNumText.Text = e.Row.Cells[intIdx].Text;
                     e.Row.Cells[intIdx].Controls.Add(objNumText);
                  }
               }
               intIdx++;
            }
         }
         else
         {
            foreach (DataControlFieldCell dc in e.Row.Cells)
            {
               if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "idPersonal" && ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "dsApeNombres" && ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "dsObserva" && ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "idConRemu")
               {
                  esdNumericTextBox objNumText = new esdNumericTextBox();
                  objNumText.NumericType = NumericType.Decimal;
                  objNumText.Width = 30;
                  objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx;
                  objNumText.Text = dc.Text;
                  dc.Controls.Add(objNumText);
               }
               else
               {
                  if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField == "dsObserva")
                  {
                     esdTextBox objNumText = new esdTextBox();
                     objNumText.Width = 150;
                     objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx;
                     objNumText.Text = dc.Text;
                     dc.Controls.Add(objNumText);
                  }
                  if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField == "idConRemu")
                  {
                     esdTextBox objNumText = new esdTextBox();
                     objNumText.Width = 30;
                     objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx;
                     objNumText.Text = dc.Text;
                     dc.Controls.Add(objNumText);
                  }
               }
               intIdx++;
            }
         }
      }

      public override Object CreateEntitySet()
      {

         DataTable dt = (DataTable)this.DataSourceData;

         DataTable dtChange = null;
         dtChange = dt.GetChanges(DataRowState.Added);
         dtChange = dt.GetChanges(DataRowState.Modified);

         IList<EProcPlaHora> colEProcPlaH = new List<EProcPlaHora>();
         foreach (GridViewRow gvr in this.grdListData.Rows)
         {
            if (gvr.RowType == DataControlRowType.DataRow)
            {
               string strIdPer = "";
               if (this.StDatosGenerados == ConstFlagEstado.ACTIVADO)
               {
                  int intinx = 0;
                  foreach (DataRow drcol in this.DataSource.Rows)
                  {

                     if (drcol["stIdPersonal"].ToString() == ConstFlagEstado.ACTIVADO)
                     {
                        strIdPer = "0000000" + gvr.Cells[intinx].Text;
                        strIdPer = strIdPer.Substring(strIdPer.Length - 7, 7);
                     }
                     else
                        if (drcol["idHora"].ToString() != "")
                        {
                           EProcPlaHora objE = new EProcPlaHora();
                           objE.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
                           objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                           objE.IdForPago = Request.QueryString["idForPago"];
                           objE.IdPlanilla = Request.QueryString["IdPlanilla"];
                           objE.NuProcAnual = int.Parse(Request.QueryString["NuProcAnual"]);
                           objE.IdPersonal = strIdPer;
                           objE.IdHora = drcol["idHora"].ToString();
                           objE.NuHoras = decimal.Parse(gvr.Cells[intinx].Text);
                           objE.StAnulado = ConstFlagEstado.DESACTIVADO;
                           objE.EntityState = EntityState.Added;
                           colEProcPlaH.Add(objE);
                        }
                     intinx++;
                  }

               }
               else
               {
                  foreach (DataControlFieldCell dc in gvr.Cells)
                  {
                     if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField == "idPersonal")
                     {
                        strIdPer = "0000000" + dc.Text;
                        strIdPer = strIdPer.Substring(strIdPer.Length - 7, 7);
                     }
                     else
                     {
                        if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "dsApeNombres")
                        {
                           EProcPlaHora objE = new EProcPlaHora();
                           objE.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
                           objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                           objE.IdForPago = Request.QueryString["idForPago"];
                           objE.IdPlanilla = Request.QueryString["IdPlanilla"];
                           objE.NuProcAnual = int.Parse(Request.QueryString["NuProcAnual"]);
                           objE.IdPersonal = strIdPer;
                           objE.IdHora = ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField;
                           objE.NuHoras = decimal.Parse(dc.Text);
                           objE.StAnulado = ConstFlagEstado.DESACTIVADO;
                           objE.EntityState = EntityState.Modified;
                           colEProcPlaH.Add(objE);
                        }

                     }
                  }

               }

            }
         }

         EProcPlaHoraSet objESet = new EProcPlaHoraSet();
         objESet.EProcPlaHora = colEProcPlaH;
         return objESet;
      }

      public override void LockControls()
      {
          if (Request.QueryString["StProceso"] == ConstEstadoProcePlani.CERRADA)
              this.mnuToolbar.Enabled = false;
      }

   }
}